package com.budwk.app.oss.services.impl;

import cn.dev33.satoken.context.SaTokenContextForThreadLocalStorage;
import cn.dev33.satoken.context.model.SaRequest;
import cn.dev33.satoken.context.model.SaStorage;
import cn.dev33.satoken.stp.StpLogic;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.budwk.app.base.filedetection.FileDetection;
import com.budwk.app.exception.ServiceException;
import com.budwk.app.oss.config.HuaweiyunOss;
import com.budwk.app.oss.models.SysOss;
import com.budwk.app.oss.services.SysOssService;
import com.budwk.app.sqfw.component.CommonComponent;
import com.budwk.app.sys.models.Sys_user;
import com.budwk.app.sys.services.SysUserService;
import com.budwk.app.util.ThreadLocalUtil;
import com.budwk.app.util.poiUtils.nutzBeanUtils.NutzIocUtils;
import com.budwk.starter.common.page.Pagination;
import com.budwk.starter.database.service.BaseServiceImpl;
import com.budwk.starter.security.utils.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.nutz.dao.Condition;
import org.nutz.dao.Dao;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.upload.TempFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Slf4j
@IocBean(args = {"refer:dao"})
public class SysOssServiceImpl extends BaseServiceImpl<SysOss> implements SysOssService {

    public static final String SERVICE_ARGS = "service_args";// 服务参数配置

    public static final String OSS_SOURCE_URL = "oss_source_url";// 存储对象源地址

    public static final String OSS_MAPPING_URL = "oss_mapping_url";// 存储对象映射地址

    @Inject
    private HuaweiyunOss huaweiyunOss;

    @Inject
    private FileDetection fileDetection;

    @Inject
    private SysUserService sysUserService;

    public SysOssServiceImpl(Dao dao) {
        super(dao);
    }

    @Override
    public Pagination queryPageList(int pageNumber, int pageSize, Condition cnd) {
        return null;
    }

    @Override
    public List<SysOss> listByIds(Collection<Long> ossIds) {
        return null;
    }

    @Override
    public SysOss getById(Long ossId) {
        return null;
    }

    @Override
    public SysOss upload(TempFile file) {
        String userId ="";

        String originalFileName = file.getSubmittedFileName();
        String suffix = StringUtils.substring(originalFileName, originalFileName.lastIndexOf("."), originalFileName.length());
        String fileName = HuaweiyunOss.getFileName(suffix);
        //上传文件
        String url = huaweiyunOss.upload(file.getFile(), fileName);
        SysOss oss = new SysOss();
        oss.setOssId(IdUtil.getSnowflakeNextId());
        oss.setUrl(url);
        oss.setFileSuffix(suffix);
        oss.setFileName(fileName);
        oss.setOriginalName(originalFileName);
        oss.setService(HuaweiyunOss.CONFIG_KEY);
        try {
            userId =   SecurityUtil.getUserId();
        } catch (Exception e) {
            userId = ThreadLocalUtil.getUserId();
        }
        try {
            Sys_user sysUser = sysUserService.fetch(userId);
            oss.setProvince(sysUser.getProvince());
            oss.setCity(sysUser.getCity());
            oss.setDistrict(sysUser.getDistrict());
            oss.setCounty(sysUser.getCounty());
            oss.setCommunity(sysUser.getCommunity());
        } catch (Exception e) {
            log.info("sysoss:"+e.getMessage());
        }
        oss.setCreateTime(new Date());
        oss.setUpdateTime(new Date());
        this.insert(oss);
        return oss;
    }

    @Override
    public SysOss uploadNotUUID(TempFile file, String fileName) {
        String userId ="";

        String originalFileName = file.getSubmittedFileName();
        String suffix = StringUtils.substring(originalFileName, originalFileName.lastIndexOf("."), originalFileName.length());
        fileName = HuaweiyunOss.getFileNameNotUUID(suffix, fileName.substring(0, fileName.lastIndexOf(".")));
        //上传文件
        String url = huaweiyunOss.upload(file.getFile(), fileName);
        SysOss oss = new SysOss();
        oss.setOssId(IdUtil.getSnowflakeNextId());
        oss.setUrl(url);
        oss.setFileSuffix(suffix);
        oss.setFileName(fileName);
        oss.setOriginalName(originalFileName);
        oss.setService(HuaweiyunOss.CONFIG_KEY);
        try {
            userId =   SecurityUtil.getUserId();
        } catch (Exception e) {
            userId = ThreadLocalUtil.getUserId();
        }
        try {
            Sys_user sysUser = sysUserService.fetch(userId);
            oss.setProvince(sysUser.getProvince());
            oss.setCity(sysUser.getCity());
            oss.setDistrict(sysUser.getDistrict());
            oss.setCounty(sysUser.getCounty());
            oss.setCommunity(sysUser.getCommunity());
        } catch (Exception e) {
            log.info("sysossException:"+e.getMessage());
        }
        oss.setCreateTime(new Date());
        oss.setUpdateTime(new Date());
        this.insert(oss);
        return oss;
    }

    @Override
    public SysOss upload(byte[] bytes, String fileName) {
        if (StringUtils.isBlank(fileName)) return null;
        int lastSymbolIndex = fileName.lastIndexOf(".");
        if (lastSymbolIndex == fileName.length() - 1) return null;

        String suffix = fileName.substring(lastSymbolIndex + 1);
        fileName = HuaweiyunOss.getFileName(suffix, fileName.substring(0, fileName.lastIndexOf(".")));
        //上传文件
        String url = huaweiyunOss.upload(bytes, fileName);
        if (StringUtils.isNotEmpty(url) && url.startsWith("http")) {
            String huaweiOssPrefix = NutzIocUtils.getOssPrefixHuaWei();
            String proxy = NutzIocUtils.getOssPrefix();
            url = url.replace(huaweiOssPrefix,"").replace(proxy,"");
        }
        SysOss oss = new SysOss();
        String userId ="";
        try {
            userId =   SecurityUtil.getUserId();
        } catch (Exception e) {
            userId = ThreadLocalUtil.getUserId();
        };
        try {
            Sys_user sysUser = sysUserService.fetch(userId);
            oss.setProvince(sysUser.getProvince());
            oss.setCity(sysUser.getCity());
            oss.setDistrict(sysUser.getDistrict());
            oss.setCounty(sysUser.getCounty());
            oss.setCommunity(sysUser.getCommunity());
        } catch (Exception e) {
            log.info("sysossException:"+e.getMessage());
        }
        oss.setOssId(IdUtil.getSnowflakeNextId());
        oss.setUrl(url);
        oss.setFileSuffix(suffix);
        oss.setFileName(fileName);
        oss.setOriginalName(fileName);
        oss.setService(HuaweiyunOss.CONFIG_KEY);
        oss.setCreateTime(new Date());
        oss.setUpdateTime(new Date());
        this.insert(oss);
        return oss;
    }

    @Override
    public List<SysOss> uploads(List<TempFile> files) {
        return null;
    }

    @Override
    public SysOss upload(File file) {
        /*try {
            //文件上传检测
            fileDetection.uploadFileDetection(file);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }*/

        String originalFileName = file.getName();
        String suffix = StringUtils.substring(originalFileName, originalFileName.lastIndexOf("."), originalFileName.length());
        String fileName = HuaweiyunOss.getFileName(suffix);
        //上传文件
        String url = huaweiyunOss.upload(file, fileName);
        SysOss oss = new SysOss();
        oss.setOssId(IdUtil.getSnowflakeNextId());
        oss.setUrl(url);
        oss.setFileSuffix(suffix);
        oss.setFileName(fileName);
        oss.setOriginalName(originalFileName);
        oss.setService(HuaweiyunOss.CONFIG_KEY);
        String userId ="";
        try {
            userId =   SecurityUtil.getUserId();
        } catch (Exception e) {
            userId = ThreadLocalUtil.getUserId();
        }
        try {
            Sys_user sysUser = sysUserService.fetch(userId);
            oss.setProvince(sysUser.getProvince());
            oss.setCity(sysUser.getCity());
            oss.setDistrict(sysUser.getDistrict());
            oss.setCounty(sysUser.getCounty());
            oss.setCommunity(sysUser.getCommunity());
        } catch (Exception e) {
            log.info("sysossException:"+e.getMessage());
        }
        oss.setCreateTime(new Date());
        oss.setUpdateTime(new Date());
        this.insert(oss);
        return oss;
    }

    @Override
    public SysOss upload(File file, String fileName) {
        String userId ="";

        String originalFileName = fileName;
        String suffix = StringUtils.substring(originalFileName, originalFileName.lastIndexOf("."), originalFileName.length());
        fileName = HuaweiyunOss.getFileName(suffix, fileName);
        //上传文件
        String url = huaweiyunOss.upload(file, fileName);
        SysOss oss = new SysOss();
        oss.setOssId(IdUtil.getSnowflakeNextId());
        oss.setUrl(url);
        oss.setFileSuffix(suffix);
        oss.setFileName(fileName);
        oss.setOriginalName(originalFileName);
        try {
            userId =   SecurityUtil.getUserId();
        } catch (Exception e) {
            userId = ThreadLocalUtil.getUserId();
        }
        try {
            Sys_user sysUser = sysUserService.fetch(userId);
            oss.setProvince(sysUser.getProvince());
            oss.setCity(sysUser.getCity());
            oss.setDistrict(sysUser.getDistrict());
            oss.setCounty(sysUser.getCounty());
            oss.setCommunity(sysUser.getCommunity());
        } catch (Exception e) {
            log.info("sysossException:"+e.getMessage());
        }
        oss.setService(HuaweiyunOss.CONFIG_KEY);
        oss.setCreateTime(new Date());
        oss.setUpdateTime(new Date());
        this.insert(oss);
        return oss;
    }

    @Override
    public void download(Long ossId, HttpServletResponse response) throws IOException {
        SysOss sysOss = this.getById(ossId);
        if (ObjectUtil.isNull(sysOss)) {
            throw new ServiceException("文件数据不存在!");
        }
        InputStream inputStream = huaweiyunOss.download(sysOss.getFileName());
        int available = inputStream.available();
        IoUtil.copy(inputStream, response.getOutputStream(), available);
        response.setContentLength(available);
    }

    @Override
    public InputStream download(String fileName) throws IOException {
        if (ObjectUtil.isNull(fileName)) {
            throw new ServiceException("文件数据不存在!");
        }
        InputStream inputStream = huaweiyunOss.download(fileName);
        return inputStream;
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        return null;
    }

    /**
     * 获取服务参数
     *
     * @return
     */
    public static Map<String, String> getOSSServiceArgs() {
        return CommonComponent.getDictMap(SERVICE_ARGS);
    }


    @Override
    public SysOss uploadFileName(TempFile file, String fileName) {
        String originalFileName = file.getSubmittedFileName();
        String userId ="";

        String suffix = StringUtils.substring(originalFileName, originalFileName.lastIndexOf("."), originalFileName.length());
         if (null != fileName && suffix!=null) {
             fileName=fileName+suffix;
         }else{
             fileName = HuaweiyunOss.getFileName(suffix);
         }
        //上传文件
        String url = huaweiyunOss.upload(file.getFile(), fileName);
        if (StringUtils.isNotEmpty(url) && url.startsWith("http")) {
            String huaweiOssPrefix = NutzIocUtils.getOssPrefixHuaWei();
            String proxy = NutzIocUtils.getOssProxy();
            url = url.replace(huaweiOssPrefix,"").replace(proxy,"");
        }
        SysOss oss = new SysOss();
        oss.setOssId(IdUtil.getSnowflakeNextId());
        oss.setUrl(url);
        oss.setFileSuffix(suffix);
        oss.setFileName(fileName);
        oss.setOriginalName(originalFileName);

        try {
            userId =   SecurityUtil.getUserId();
        } catch (Exception e) {
            userId = ThreadLocalUtil.getUserId();
        }
        try {
            Sys_user sysUser = sysUserService.fetch(userId);
            oss.setProvince(sysUser.getProvince());
            oss.setCity(sysUser.getCity());
            oss.setDistrict(sysUser.getDistrict());
            oss.setCounty(sysUser.getCounty());
            oss.setCommunity(sysUser.getCommunity());
        } catch (Exception e) {
            log.info("sysossException:"+e.getMessage());
        }
        oss.setService(HuaweiyunOss.CONFIG_KEY);
        oss.setCreateTime(new Date());
        oss.setUpdateTime(new Date());
        this.insert(oss);
        return oss;
    }
}
